<?php

namespace app\common\controller;

use think\Controller;

class Upload extends controller
{
    public function image($type = 0){
        $dir = './uploads/images/';
        $file = request()->file('file');
        if (empty($file)) return false;
        $info = $file->validate(['ext' => 'jpg,jpeg,png,gif'])
            ->move($dir, true, false);
        if ($info) {
            $result = $this->COSUploadFile('images/' . date('Ymd') . '/' . $info->getFilename(), 'http://'.$_SERVER['HTTP_HOST'].$dir . $info->getSaveName());
           
            unlink($dir . $info->getSaveName());
            if ($result['state'] == 1) {
                // $data = ['url' => $result['url'], 'name' => $info->getFilename(), 'ext' => $info->getExtension()];
                // return ['state' => 1, 'msg' => '上传成功', 'data' => $data];
               return  ['url' => $result['url'],'name' => $result['url'], 'ext' => $info->getExtension()];
            } else {
                return $result;
            }
        } else {
            return $file->getError();
        }
    }
   
       /**
     * 上传到OSS存储
     *
     * @param [type] $object    文件名
     * @param [type] $Path      本地文件路径
     * @return void
     */
    function COSUploadFile($object, $local_path)
    {
        $cosClient = new \Qcloud\Cos\Client(
            array(
                'region' => config('cos.CosRegion'),
                'schema' => 'http', //协议头部，默认为http
                'credentials' => array(
                    'secretId'  => config('cos.CosSecretId'),
                    'secretKey' => config('cos.CosSecretKey')
                )
            )
        );
       
        $path = "./".time().".png";
        $this->html($local_path,$path);
        
        try {
            $result = $cosClient->upload(config('cos.CosBucket'), $object, fopen($path, 'rb'));
            // $result = $cosClient->upload(config('cos.CosBucket'), $object,$path);
            // 请求成功
            unlink($path);
            return ['state' => 1, 'url' => 'https://' . $result['Location']];
        } catch (\Exception $e) {
            return ['state' => 0, 'msg' => $e->getMessage()];
        }
    }
    public function html($url,$savePath){

        $ch = curl_init($url);
        $fp = fopen($savePath, 'wb');
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_exec($ch);
        curl_close($ch);
        fclose($fp);
    }

}
